import Clear from './commonds/Clear';
import Main from './Main';//仅用于代码提示
export default class Cmd{
	/**
	 * 
	 * @param {Main} main 
	 */
	constructor(main){
		this.name = "命令行模块";
		this.id = "cmd";
		this.version = "0.4"; //模块版本
		this.program = "0.6.0"; //本模块是为该版本的主程序设计
		this.enviornment=main;
		this.commands= {
			clear: new Clear(this),
			help: {
				help: "查看帮助",
				run: function (par) {
					this.help();
				}
			},
			/*init:{
				help:"初始化坐标系",
				run:function(par){
				}
			}*/
		};//命令列表
	}
	consoleMsg(msg){
		this.enviornment.consoleMsg(msg);
	}
	log(model,msg){
		this.enviornment.log(model,msg);
	}
	
	init(){
		let that=this;
		document.getElementById("run").onclick=function(){
			that.run();
		}
		document.getElementById("cmd").onkeypress=function(e){
				if(e.which==13 ||e.KeyCode==13){
					that.run();
				}
		}
	}
	help(){
		for(var a in cmd.commands){
			if(a.length>8){
				b="\t"+a+"\t";
			}else{
				b="\t"+a+"\t\t";
			}
			this.consoleMsg("\t"+b+"\t\t"+cmd.commands[a].help);
		}
	}
	run(){
		let inputCmd=document.getElementById("cmd").value;
		document.getElementById("cmd").value="";
		//先进行语义分析
		//以任意数量个空格为标志，把字符串切碎，放进数组里。
		let cmdStr=inputCmd.split(/\s+/);
		//最前面和最后面可能有空格,会产生空字符串。先消灭空字符。
		while(cmdStr[0]==""){
			for(i=0;cmdStr[i]!=undefined;i++){
				cmdStr[i]=cmdStr[i+1];
			}
		}
		while(cmdStr[cmdStr.length-1]==""){
			cmdStr.pop();
		}
		//除了带引号的，其它全部转换为小写
		let i=0;
		while(cmdStr[i]){
			if(!cmdStr[i].match(/('|")[A-z]+('|")/)){
				cmdStr[i]=cmdStr[i].toLowerCase();
			}
			i++;
		}
		//剪切出第一个元素，也就是指令名称
		let cmdName=cmdStr.shift();
		//开始执行~~
		this.consoleMsg("\n Commond->"+inputCmd);
		if(!this.commands[cmdName]){
			this.consoleMsg(cmd.name+"信息：不存在的指令。请输入help获取帮助。");
		}else{
			this.commands[cmdName].run(cmdStr);
		}
	}
}

